#!/usr/bin/env python
"""
# -*- coding: utf-8 -*-
# @Time    : 2020/9/30 17:10
# @Author  : AshJo
# @Desc    : 客户端
# @Filename: client.py
# @Version : v1.0
"""

# 发送文件
import os
import socket
import json
import struct
import hmac

secret_key = b'ashjo_233'
sk = socket.socket()
sk.connect(('127.0.0.1', 9000))

"""验证客户端合法性"""
# 接收服务端发送的随机字符串
rand = sk.recv(32)

# 摘要计算后并把结果发送回server
h = hmac.new(secret_key, rand)
ret = h.digest()
sk.send(ret)

# 文件名/文件大小
abs_path = r'D:\VScode\Python\Project\Python_fullstack\day30\tmp'
filename = os.path.basename(abs_path)
filesize = os.path.getsize(abs_path)

dic = {'filename': filename, 'filesize': filesize}
str_dic = json.dumps(dic)
b_dic = str_dic.encode('utf-8')
mlen = struct.pack('i', len(b_dic))
sk.send(mlen)  # 4个字节 表示字典转成字节之后的长度
sk.send(b_dic)  # 具体的字典数据

"""发送小文件"""
# with open(abs_path, mode='rb') as f:
#     content = f.read()
#     sk.send(content)
"""发送大文件"""
with open(abs_path, mode='rb') as f:
    while filesize > 0:
        content = f.read(1024)
        filesize -= len(content)
        sk.send(content)

sk.close()
